//
//  MXMyHomeViewController.m
//  HNBaseProject
//
//  Created by AAA on 2024/6/5.
//

#import "MXMyHomeViewController.h"
#import "MxPublicNav.h"
#import "MXMyHomeTableHeadView.h"
#import "MXMyHomeCell.h"
#import "MXMyHomeAddCell.h"
#import "DCAlterView.h"
#import "MXAddUserViewController.h"
#import "MXShiftInController.h"
#import "MXHomeEquimentListController.h"
#import "MXSearchUserModel.h"
@interface MXMyHomeViewController () <MxNavigationViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MxPublicNav *nav;
@property (nonatomic, strong) MXMyHomeTableHeadView *headView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSString *homeName;
@property (nonatomic, strong) NSMutableArray *userArray;
@end

@implementation MXMyHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor systemGray6Color];
    self.homeName = @"";
    self.userArray = [[NSMutableArray alloc] init];
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = SAFEPARAMETER(self.homeModel.familyName);
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    
//    YWPersonalTableHeaderView *headerView = [YWPersonalTableHeaderView getView];
//    self.headerView = headerView;
//    headerView.frame =CGRectMake(0,0,kScreenWidth, kstatusHeight + 320);

    
    MJWeakSelf
//    self.headView = [MXMyHomeTableHeadView dc_viewFromXib];
    MXMyHomeTableHeadView *hedV = [MXMyHomeTableHeadView dc_viewFromXib];
    hedV.frame = CGRectMake(0, 0, kScreenW-30, 128);
    self.headView = hedV;
//    self.headView.nameField.delegate = self;
    [self.headView.nameField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.headView.nameField addTarget:self action:@selector(textFieldDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
    
    self.headView.deviceLab.userInteractionEnabled = YES;
    [self.headView.deviceLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf gotoDeviceList];
    }]];
    
    self.tableView.tableHeaderView = self.headView;
    UIView *hView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW-30, 128)];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [hView addSubview:hedV];
    });
    
    self.tableView.tableHeaderView.frame = CGRectMake(0, 0, kScreenW-30, 128);
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MXMyHomeCell" bundle:nil] forCellReuseIdentifier:@"MXMyHomeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MXMyHomeAddCell" bundle:nil] forCellReuseIdentifier:@"MXMyHomeAddCell"];
    
    self.headView.nameField.text = SAFEPARAMETER(self.homeModel.familyName);
    self.headView.deviceLab.text = [NSString stringWithFormat:@"%ld个设备",self.count];//@"0个设备";
    self.tableView.tableHeaderView= hView;
    [self getUserList];
}

- (void)getUserList {

    NSString *urlStr = [NSString stringWithFormat:@"%@?familyId=%@&pageNum=%@&pageSize=%@",@"api/app/family/queryFamilyUserList",SAFEPARAMETER(self.homeModel.familyId),@"1",@"20"];
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            
            NSArray *dataArray =  [NSArray modelArrayWithClass:[MXSearchUserModel class] json:dict[@"data"][@"list"]];
            [weakSelf.userArray addObjectsFromArray:dataArray];
//            MXUserInfoModel *user = [DCCacheTool getCurrentUserInfo];
//            for (int i =0; i < dataArray.count; i++) {
//                MXSearchUserModel *model = dataArray[i];
//                if (![model.ID isEqualToString:user.ID]) {
//                    [weakSelf.userArray addObject:model];
//                }
//            }
            [weakSelf.tableView reloadData];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    self.homeName = textField.text;
}

- (void)textFieldDidEnd:(UITextField *)textField {
    if (textField.text.length == 0) {
        [self.view xjmakeToast:@"请输入家庭名称"];
        self.headView.nameField.text = SAFEPARAMETER(self.homeModel.familyName);
        return;
    }
    [self updateUserInfo:textField.text];
}

- (void)updateUserInfo:(NSString *)text {

    NSDictionary *param = @{@"familyAddress":SAFEPARAMETER(self.homeModel.familyAddress),
                            @"familyName":SAFEPARAMETER(text),
                            @"id":SAFEPARAMETER(self.homeModel.familyId)};
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/family/update" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            weakSelf.headView.nameField.text = text;
            weakSelf.homeModel.familyName = text;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updatehomename" object:nil];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
    
}

- (void)gotoDeviceList {
    MXHomeEquimentListController * listVc = [[MXHomeEquimentListController alloc] init];
    listVc.hmodel = self.homeModel;
    [self.navigationController pushViewController:listVc animated:YES];
//    MXShiftInController *vc = [[MXShiftInController alloc] init];
//    vc.homeName = self.homeModel.familyName;
//    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - MXMyHomeTableHeadViewDelegate
- (void)myHomeDidEnd:(UITextField *)sender {
    
//    [SVProgressHUD dc_showInfoWithStatus:@"家庭名称输入结束"];
}

- (void)homeDeviceButtonClick:(UIButton *)sender {
    
//    [SVProgressHUD dc_showInfoWithStatus:@"点击了家庭设备"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

- (IBAction)toHomeButtonClick:(id)sender {
    
//    [SVProgressHUD dc_showInfoWithStatus:@"点击了进入家庭"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"enterhome" object:@{@"familyId":self.homeModel.familyId}];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)dissolveHomeButtonClick:(id)sender {
    
//    [SVProgressHUD dc_showInfoWithStatus:@"点击了解散家庭"];
    [self removeCurrentHome];
}
- (void)removeCurrentHome {

    MJWeakSelf
    [self.view makeToastActivity];
    NSString *urlStr = [NSString stringWithFormat:@"%@?id=%@",@"api/app/family/remove",self.homeModel.familyId];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updatehomename" object:nil];
            [weakSelf .navigationController popViewControllerAnimated:YES];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.userArray.count + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    
    // 获取 section 中的行数
    NSInteger rowsInSection = [tableView numberOfRowsInSection:indexPath.section];
    
    if (rowsInSection == indexPath.row + 1) {
        
        MXMyHomeAddCell* cell = [tableView dequeueReusableCellWithIdentifier:@"MXMyHomeAddCell" forIndexPath:indexPath];
        return cell;
    } else {
        MXSearchUserModel *model = self.userArray[indexPath.row];
        MXMyHomeCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MXMyHomeCell" forIndexPath:indexPath];
        MXUserInfoModel *user = [DCCacheTool getCurrentUserInfo];
        if ([model.ID isEqualToString:user.ID]) {
            cell.nameLab.text = [NSString stringWithFormat:@"%@(我)",model.username];
        } else {
            cell.nameLab.text = model.username;
        }
        cell.createLab.hidden = ![model.ID isEqualToString:self.homeModel.createUserId];
        return cell;
    }
        
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 获取 section 中的行数
    NSInteger rowsInSection = [tableView numberOfRowsInSection:indexPath.section];
    
    // 判断当前 cell 是否是 section 中的第一个 cell
    BOOL isFirstCell = indexPath.row == 0;
    // 判断当前 cell 是否是 section 中的最后一个 cell
    BOOL isLastCell = (rowsInSection == indexPath.row + 1);
    
    // 根据位置设置圆角
    if (isFirstCell && isLastCell) {
        // 只有一个 cell，四个角都要设置圆角
        [cell setRoundedCorners];
    } else if (isFirstCell) {
        // section 中的第一个 cell，设置上左上右为圆角
        [cell setTopRoundedCorners];
    } else if (isLastCell) {
        // section 中的最后一个 cell，设置下左下右为圆角
        [cell setBottomRoundedCorners];
    } else {
        // 中间的 cell，取消圆角
        [cell resetRoundedCorners];
    }

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return [NSString stringWithFormat:@"%ld个成员",self.userArray.count];//@"1个成员";
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 获取 section 中的行数
    NSInteger rowsInSection = [tableView numberOfRowsInSection:indexPath.section];
    
    if (rowsInSection == indexPath.row + 1) {
        
        WEAKSELF
        DCAlterView * alterView = [[DCAlterView alloc] initWithTitle:@"" content:@"成员可以使用此家庭下所有设备、查看宠物详情，赶快添加成员一起管理设备和宠物吧~"];
        [alterView addActionWithTitle:@"取消" color:[UIColor colorWithHexString:@"#3378F8"] type:DCAlterTypeCancel halderBlock:^(UIButton *button) {
                
        }];
        [alterView addActionWithTitle:@"去添加" color:[UIColor colorWithHexString:@"#3378F8"] type:DCAlterTypeDone halderBlock:^(UIButton *button) {

            MXAddUserViewController *vc = [[MXAddUserViewController alloc] init];
            vc.inviteFamilyId = weakSelf.homeModel.familyId;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        
        [DC_KeyWindow addSubview:alterView];
        
    } else {
        
//        [SVProgressHUD dc_showInfoWithStatus:@"点击了cell"];
    }
}


#pragma mark - MxNavigationViewDelegate
- (void)leftTap {
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
